import list from './js/data.js';
import './css/index.css';
// 图片列表
let ul = document.querySelector('.content > ul');
// 上一页
let prevBtn = document.querySelector('.prev');
// 下一页
let nextBtn = document.querySelector('.next');
// 总页
let totalBox = document.querySelector('.total');
// 选择框
let selectBox = document.querySelector('select');
// 选中的页数
let selectNum = 0;
// 总页数
let totalPage = 0;
// 当前页数
let pageIndex = 1;
// 要展示的数据
let pageData = [];

// 初始化页数和数据
changePage();
showData();

// 更改总页数方法
function changePage() {
  selectNum = Math.floor(selectBox.value);
  totalPage = Math.ceil(list.length / selectNum);
  totalBox.innerText = `${pageIndex} / ${totalPage}`;
  if (pageIndex >= totalPage) {
    pageIndex = totalPage;
    totalBox.innerText = `${pageIndex} / ${totalPage}`;
    nextBtn.classList.add('disable');
  } else {
    nextBtn.classList.remove('disable');
  }
}

// 显示数据
function showData() {
  // 截取开始坐标
  let startIndex = Math.floor((pageIndex - 1) * selectNum);
  // 截取结束坐标
  let endIndex = Math.floor(startIndex + selectNum);
  // 要显示的数据
  pageData = list.slice(startIndex, endIndex);
  // 数组遍历渲染图片
  pageData.forEach((el, index) => {
    let li = document.createElement('li');
    let img = document.createElement('img');
    let name = document.createElement('p');
    let city = document.createElement('p');
    let address = document.createElement('p');
    let price = document.createElement('p');
    let showTime = document.createElement('p');
    img.src = `${pageData[index].pic}`;
    name.innerText = `${pageData[index].name}`;
    city.innerText = `城市：${pageData[index].city}`;
    address.innerText = `地址：${pageData[index].address}`;
    price.innerText = `价格：${pageData[index].price}`;
    showTime.innerText = `演出时间：${pageData[index].showTime}`;
    ul.append(li);
    li.append(img);
    li.append(name);
    li.append(city);
    li.append(address);
    li.append(price);
    li.append(showTime);
  });
}

// 清除数据方法
function clearData() {
  Array.from(ul.children).forEach((el) => {
    el.remove();
  });
}

// 下拉框选择事件
selectBox.addEventListener('change', () => {
  clearData();
  changePage();
  showData();
});

// 下一页点击事件
nextBtn.addEventListener('click', () => {
  if (pageIndex < totalPage) {
    pageIndex++;
    prevBtn.classList.remove('disable');
    totalBox.innerText = `${pageIndex} / ${totalPage}`;
    clearData();
    showData();
  }
  if (pageIndex == totalPage) {
    nextBtn.classList.add('disable');
  }
});

// 上一页点击事件
prevBtn.addEventListener('click', () => {
  if (pageIndex > 1) {
    pageIndex--;
    prevBtn.classList.remove('disable');
    nextBtn.classList.remove('disable');
    totalBox.innerText = `${pageIndex} / ${totalPage}`;
    clearData();
    showData();
  }
  if (pageIndex == 1) {
    prevBtn.classList.add('disable');
  }
});
